package com.fastCms.business.frame.plugins.oss;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@Slf4j
@Service
public class OssTencentServiceImpl implements OssTencentService {


    @Value("${tencent.accessKeyId}")
    private String accessKeyId;

    @Value("${tencent.accessSecret}")
    private String accessSecret;

    @Value("${tencent.oss.endpoint}")
    private String endpoint;

    @Value("${tencent.oss.region}")
    private String ossRegion;

    private static COSClient client;

    @PostConstruct
    public void init() {
        // 1 初始化用户身份信息（secretId, secretKey）。
// SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        COSCredentials cred = new BasicCOSCredentials(accessKeyId, accessSecret);
// 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(ossRegion);
        ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
        client = new COSClient(cred, clientConfig);
    }

    @Override
    public String uploadFile(String bucketName, String objectName, MultipartFile multipartFile) throws Exception {
        try {

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, multipartFile.getInputStream(), null);
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);

            StringBuilder sb = new StringBuilder();
            sb.append("https://").append(endpoint).append("/")
                    .append(URLEncoder.encode(objectName, "UTF-8"));
            return URLDecoder.decode(sb.toString(), "utf-8");

        } catch (Exception oe) {
            log.error("[OSS文件上传失败]" + oe.getMessage(), oe);
            throw new Exception("OSS文件上传失败");
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
    }
}
